package com.cgw.game.ui;

import android.Manifest;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.media.projection.MediaProjectionManager;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.util.DisplayMetrics;
import android.view.View;
import android.widget.Button;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import com.cgw.game.R;
import com.cgw.game.service.ScreenRecorderService;
import com.cgw.game.view.ShadowView;

import java.util.ArrayList;
import java.util.List;

import me.weyye.hipermission.HiPermission;
import me.weyye.hipermission.PermissionCallback;
import me.weyye.hipermission.PermissionItem;

public class ScreenRecorderActivity extends AppCompatActivity {
    MediaProjectionManager projectionManager;
    private Button btn;
    private int hight,wight;
    private int mScreenDensity;
    private ScreenRecorderService.ScreenRecorder service;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_screen_recorder);
        Toolbar toolbar = findViewById(R.id.toolbar);
        toolbar.setTitle(getIntent().getStringExtra("title"));
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);//左侧添加一个默认的返回图标
        getSupportActionBar().setHomeButtonEnabled(true); //设置返回键可用
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();//返回
            }
        });
        ShadowView shadow = findViewById(R.id.shadow);
        shadow.setAngel(720);

        DisplayMetrics metrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metrics);
        wight = metrics.widthPixels;
        hight = metrics.heightPixels;
        mScreenDensity = metrics.densityDpi;
        List<PermissionItem> permissions = new ArrayList<>();
        permissions.add(new PermissionItem(Manifest.permission.RECORD_AUDIO, "屏幕录制", R.drawable.permission_ic_camera));
        permissions.add(new PermissionItem(Manifest.permission.WRITE_EXTERNAL_STORAGE, "内存写入", R.drawable.permission_ic_storage));
        permissions.add(new PermissionItem(Manifest.permission.READ_EXTERNAL_STORAGE, "内存写入", R.drawable.permission_ic_storage));
        HiPermission.create(this)
                .title("录屏权限申请")
                .permissions(permissions)
                .msg("录屏需要如下权限,未授予权限会录屏失败")
                .style(R.style.PermissionDefaultNormalStyle)
                .checkMutiPermission(new PermissionCallback() {
                    @Override
                    public void onClose() {

                    }

                    @Override
                    public void onFinish() {
                        initView();
                    }

                    @Override
                    public void onDeny(String permission, int position) {
                        finish();
                    }

                    @Override
                    public void onGuarantee(String permission, int position) {
                        initView();
                    }
                });
    }
    /**
     * 初始化页面
     * */
    private void initView() {
        if(projectionManager!=null){
            return;
        }
        projectionManager = (MediaProjectionManager) getSystemService(MEDIA_PROJECTION_SERVICE);
        Intent captureIntent= projectionManager.createScreenCaptureIntent();
        startActivityForResult(captureIntent, 1);
        btn = findViewById(R.id.recorder);
        btn.setText("开始");
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(service!=null){
                    if(service.isStart()){
                        service.stop();
                        btn.setText("开始");
                    }else {
                        service.start();
                        btn.setText("结束");
                    }
                }
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1 && resultCode == RESULT_OK) {
            Intent service = new Intent(this, ScreenRecorderService.class);
            service.putExtra("code", resultCode);
            service.putExtra("data", data);
            service.putExtra("hight", hight);
            service.putExtra("wight", wight);
            service.putExtra("mScreenDensity", mScreenDensity);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                startForegroundService(service);
            }else {
                startService(service);
            }
            bindService(service, connection, BIND_AUTO_CREATE);
        }
    }


    ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder ibinder) {
            service = (ScreenRecorderService.ScreenRecorder) ibinder;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };


    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbindService(connection);
    }
}
